package com.ray.controller.user;

import com.ray.pojo.User;
import com.ray.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UpdateUserController extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {

        // 获得用户ID
        int id = 0;
        if (req.getParameter("userid") != null)
        {
            // 如果是空则意味着是新增
            if (req.getParameter("userid") == "")
            {
                id = -1;
            }
            else
            {
                id = Integer.parseInt(req.getParameter("userid"));
            }
        }

        // 获得用户姓名
        String name = "";
        if (req.getParameter("name") != null)
        {
            name = req.getParameter("name");
        }

        // 获得用户性别
        int gender = 0;
        if (req.getParameter("gender") != null)
        {
            gender = Integer.parseInt(req.getParameter("gender"));
        }

        // 生成用户对象
        User user = new User(id, name, gender);

        // 创建用户操作类
        UserServiceImpl userService = new UserServiceImpl();

        // 根据id是否等于-1来决定是新增还是更新
        if (id != -1)
        {
            userService.updateUser(user);
        }
        else
        {
            userService.addUser(user);
        }

        resp.sendRedirect(req.getContextPath() + "/index");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        doGet(req, resp);
    }
}
